package CreateThreadPool;

import java.util.List;
import java.util.concurrent.*;
public class T {
    public static void main(String[] args) {
        Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量
                5,//最大线程数量
                8,//临时线程存活时间
                TimeUnit.SECONDS,//临时线程存活时间单位
                new ArrayBlockingQueue<>(4),//创建任务队列，最大存放任务数量为4
                Executors.defaultThreadFactory(),//线程工厂，用到了Executors工具类来创建默认线程工厂
                new ThreadPoolExecutor.AbortPolicy());//拒绝策略，默认策略:抛出异常

        //定义出Runnable类型的任务,此时该三个任务都被核心线程正在处理
        MyRunnable myRunnable1 = new MyRunnable();
        MyRunnable myRunnable2 = new MyRunnable();
        MyRunnable myRunnable3 = new MyRunnable();
        //这里还没到临时线程创建的时机，被放入到任务队列中等待被核心线程执行
        MyRunnable myRunnable4 = new MyRunnable();
        MyRunnable myRunnable5 = new MyRunnable();
        MyRunnable myRunnable6 = new MyRunnable();
        MyRunnable myRunnable7 = new MyRunnable();

        //此时到了临时线程创建的时机了，核心线程都在满，队列已经满了
        //创建出第一个临时线程
        MyRunnable myRunnable8 = new MyRunnable();
        //创建出第二个临时线程
        MyRunnable myRunnable9 = new MyRunnable();

        //此时核心线程都在忙，且队列已经占满了，再提交新任务的时候，
        //就会采取拒绝策略
        MyRunnable myRunnable10 = new MyRunnable();

        //将该任务提交给线程池
        threadPool.execute(myRunnable1);
        threadPool.execute(myRunnable2);
        threadPool.execute(myRunnable3);
        threadPool.execute(myRunnable4);
        threadPool.execute(myRunnable5);
        threadPool.execute(myRunnable6);
        threadPool.execute(myRunnable7);
        threadPool.execute(myRunnable8);
        threadPool.execute(myRunnable9);
        threadPool.execute(myRunnable10);

    }
}

class  MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "==> 正在执行" + this);
        try {
            //在这里等待10s
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}